import java.io.File;
import java.io.IOException;

import javax.sound.sampled.*;


public class ClipPlayer implements LineListener {

	private Clip clip;
	
	public ClipPlayer(File clipFile, int nLoopCount)
	{
		AudioInputStream audioInputStream = null;
		try
		{
			audioInputStream = AudioSystem.getAudioInputStream(clipFile);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
		if(audioInputStream != null)
		{
			AudioFormat format = audioInputStream.getFormat();
			DataLine.Info info = new DataLine.Info(Clip.class, format);
			try
			{
				clip = (Clip)AudioSystem.getLine(info);
				clip.addLineListener(this);
				clip.open(audioInputStream);
			}
			catch(LineUnavailableException e)
			{
				e.printStackTrace();
			}
			catch(IOException e)
			{
				e.printStackTrace();
			}
			clip.loop(nLoopCount);
		}
		else
		{
			System.out.println("ClipPlayer.<init>(): can't get data from file" + clipFile.getName());
		}
	}
	
	public void update(LineEvent event)
	{
		if(event.getType().equals(LineEvent.Type.STOP))
		{
			clip.close();
		}
		else if(event.getType().equals(LineEvent.Type.CLOSE))
		{
			System.exit(0);
		}
	}

}